import Holderjs from 'holderjs';
import ReactDOM from 'react-dom';
import * as React from 'react';
import _ from 'lodash';

class ImgHolder extends React.Component {
  componentDidMount() {
    if (this.isPlaceholder) {
      const holderImg = ReactDOM.findDOMNode(this.refs.holder);
      Holderjs.run({
        images: holderImg
      });
    }
  }
  componentDidUpdate() {
    this.componentDidMount();
  }

  render() {
    const { src, rect, random, size, text, ...otherProps } = this.props;
    if (!_.isEmpty(src)) {
      this.isPlaceholder = false;
      return <img src={src} {...otherProps}/>;
    }
    this.isPlaceholder = true;

    const holderParams = _.chain({ random, size, text }).map((v, k) => {
      if (v === undefined) {
        return undefined;
      }
      return `${k}=${v}`;
    }).compact().value().join('&');
    return <img {...otherProps} data-src={`holder.js/${rect}?${holderParams}`} ref='holder'/>;
  }
}

export default ImgHolder;
